package com.funsport.controller.mobile;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.funsport.common.PageResult;
import com.funsport.common.Result;
import com.funsport.dto.request.CreateClubRequest;
import com.funsport.entity.Club;
import com.funsport.entity.ClubMember;
import com.funsport.entity.User;
import com.funsport.mapper.UserMapper;
import com.funsport.security.SecurityUtils;
import com.funsport.service.IClubService;
import com.funsport.service.IClubMemberService;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@Slf4j
@Tag(name = "移动端俱乐部", description = "移动端俱乐部相关接口")
@RestController
@RequestMapping("/mobile/club")
@RequiredArgsConstructor
public class MobileClubController {

    private final IClubService clubService;
    private final IClubMemberService clubMemberService;
    private final UserMapper userMapper;
    private final com.funsport.service.WechatSecurityService securityService;

    @Operation(summary = "获取俱乐部列表")
    @GetMapping("/list")
    public Result<PageResult<Club>> getClubList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer pageSize) {
        
        Page<Club> pageParam = new Page<>(page, pageSize);
        Page<Club> result = clubService.page(pageParam, 
                new LambdaQueryWrapper<Club>()
                        .eq(Club::getStatus, "active")
                        .eq(Club::getIsPublic, true)
                        .orderByDesc(Club::getCreatedAt));

        PageResult<Club> pageResult = PageResult.build(
                result.getRecords(), 
                result.getTotal(), 
                page, 
                pageSize);

        return Result.success(pageResult);
    }

    @Operation(summary = "获取用户所属的俱乐部")
    @GetMapping("/user/my-clubs")
    public Result<List<Club>> getMyClubs() {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            return Result.error("用户未登录");
        }
        
        // 查询用户所属的俱乐部
        LambdaQueryWrapper<ClubMember> memberWrapper = new LambdaQueryWrapper<>();
        memberWrapper.eq(ClubMember::getUserId, userId);
        memberWrapper.eq(ClubMember::getStatus, "active");
        
        List<ClubMember> memberships = clubMemberService.list(memberWrapper);
        
        if (memberships.isEmpty()) {
            return Result.success(new ArrayList<>());
        }
        
        // 获取俱乐部ID列表
        List<Long> clubIds = memberships.stream()
                .map(ClubMember::getClubId)
                .collect(Collectors.toList());
        
        // 查询俱乐部详情
        List<Club> clubs = clubService.listByIds(clubIds);
        
        return Result.success(clubs);
    }

    @Operation(summary = "获取俱乐部详情")
    @GetMapping("/{id}")
    public Result<Club> getClubDetail(@PathVariable Long id) {
        Club club = clubService.getById(id);
        if (club == null) {
            return Result.error("俱乐部不存在");
        }
        return Result.success(club);
    }

    @Operation(summary = "创建俱乐部")
    @PostMapping("/create")
    public Result<Long> createClub(@Valid @RequestBody CreateClubRequest request) {
        Long userId = SecurityUtils.getCurrentUserId();
        
        // 内容安全检测 - 检测俱乐部名称和描述
        String checkText = request.getName() + " " + (request.getDescription() != null ? request.getDescription() : "");
        if (!securityService.checkText(checkText)) {
            log.warn("俱乐部名称或描述包含违规内容: userId={}", userId);
            return Result.error("俱乐部信息包含违规内容，请修改后重试");
        }
        
        Club club = new Club();
        BeanUtils.copyProperties(request, club);
        club.setCreatorId(userId);
        club.setCurrentMembers(1);
        club.setStatus("active");
        club.setPoints(0);
        club.setLevel(1);
        club.setTotalEvents(0);
        club.setTotalParticipants(0);
        
        clubService.save(club);
        
        // 创建者自动加入俱乐部，角色为管理员
        ClubMember member = new ClubMember();
        member.setClubId(club.getId());
        member.setUserId(userId);
        member.setRole("admin");
        member.setStatus("active");
        member.setJoinedAt(LocalDateTime.now());
        member.setEventsParticipated(0);
        member.setContributionPoints(0);
        clubMemberService.save(member);
        
        log.info("俱乐部创建成功: clubId={}, userId={}, 创建者自动加入为管理员", club.getId(), userId);
        
        return Result.success(club.getId());
    }

    @Operation(summary = "更新俱乐部")
    @PostMapping("/update")
    public Result<Void> updateClub(@Valid @RequestBody CreateClubRequest request) {
        Long userId = SecurityUtils.getCurrentUserId();
        
        // 检查俱乐部是否存在
        Club club = clubService.getById(request.getId());
        if (club == null) {
            return Result.error("俱乐部不存在");
        }
        
        // 检查权限：只有创建者和管理员可以编辑
        if (!club.getCreatorId().equals(userId)) {
            // 检查是否是管理员
            ClubMember member = clubMemberService.getOne(
                new LambdaQueryWrapper<ClubMember>()
                    .eq(ClubMember::getClubId, club.getId())
                    .eq(ClubMember::getUserId, userId)
                    .eq(ClubMember::getStatus, "active")
            );
            
            if (member == null || !"admin".equals(member.getRole())) {
                return Result.error("无权编辑此俱乐部");
            }
        }
        
        // 更新俱乐部信息
        BeanUtils.copyProperties(request, club);
        club.setId(request.getId()); // 确保ID不被覆盖
        clubService.updateById(club);
        
        log.info("俱乐部更新成功: clubId={}, userId={}", club.getId(), userId);
        
        return Result.success("更新成功", null);
    }

    @Operation(summary = "加入俱乐部")
    @PostMapping("/{id}/join")
    public Result<Void> joinClub(@PathVariable Long id) {
        Long userId = SecurityUtils.getCurrentUserId();
        clubMemberService.joinClub(userId, id);
        return Result.success("申请已提交", null);
    }

    @Operation(summary = "退出俱乐部")
    @PostMapping("/{id}/leave")
    public Result<Void> leaveClub(@PathVariable Long id) {
        Long userId = SecurityUtils.getCurrentUserId();
        clubMemberService.leaveClub(userId, id);
        return Result.success("已成功退出俱乐部", null);
    }

    @Operation(summary = "获取俱乐部成员列表")
    @GetMapping("/{id}/members")
    public Result<List<ClubMember>> getClubMembers(@PathVariable Long id) {
        List<ClubMember> members = clubMemberService.getClubMembers(id, "active");
        return Result.success(members);
    }

    @Operation(summary = "获取俱乐部成员详细信息", description = "包含用户头像、昵称等详细信息")
    @GetMapping("/{id}/members/detail")
    public Result<List<Map<String, Object>>> getClubMembersDetail(@PathVariable Long id) {
        try {
            // 查询所有成员
            List<ClubMember> members = clubMemberService.getClubMembers(id, "active");
            
            if (members.isEmpty()) {
                return Result.success(new ArrayList<>());
            }
            
            // 组装成员详细信息
            List<Map<String, Object>> memberDetails = new ArrayList<>();
            for (ClubMember member : members) {
                User user = userMapper.selectById(member.getUserId());
                if (user != null) {
                    Map<String, Object> memberInfo = new HashMap<>();
                    memberInfo.put("memberId", member.getId());
                    memberInfo.put("userId", user.getId());
                    memberInfo.put("nickname", user.getNickname());
                    memberInfo.put("avatar", user.getAvatar());
                    memberInfo.put("role", member.getRole());
                    memberInfo.put("status", member.getStatus());
                    memberInfo.put("eventsParticipated", member.getEventsParticipated());
                    memberInfo.put("contributionPoints", member.getContributionPoints());
                    memberInfo.put("joinedAt", member.getJoinedAt());
                    memberDetails.add(memberInfo);
                }
            }
            
            return Result.success(memberDetails);
        } catch (Exception e) {
            log.error("获取俱乐部成员详情失败: clubId={}", id, e);
            return Result.error("获取成员信息失败");
        }
    }

    @Operation(summary = "检查是否是俱乐部成员")
    @GetMapping("/{id}/is-member")
    public Result<Boolean> isMember(@PathVariable Long id) {
        Long userId = SecurityUtils.getCurrentUserId();
        boolean isMember = clubMemberService.isMember(userId, id);
        return Result.success(isMember);
    }

    @Operation(summary = "删除俱乐部", description = "只有创建者可以删除俱乐部")
    @DeleteMapping("/{id}")
    public Result<Void> deleteClub(@PathVariable Long id) {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            return Result.error("请先登录");
        }

        try {
            // 查询俱乐部
            Club club = clubService.getById(id);
            if (club == null) {
                return Result.error("俱乐部不存在");
            }

            // 检查是否是创建者
            if (!club.getCreatorId().equals(userId)) {
                return Result.error("只有俱乐部创建者可以删除俱乐部");
            }

            // 删除俱乐部（软删除，将状态改为 inactive）
            club.setStatus("inactive");
            club.setUpdatedAt(LocalDateTime.now());
            boolean success = clubService.updateById(club);

            if (success) {
                log.info("俱乐部已删除: clubId={}, userId={}", id, userId);
                return Result.success("俱乐部已删除", null);
            } else {
                return Result.error("删除俱乐部失败");
            }
        } catch (Exception e) {
            log.error("删除俱乐部失败: clubId={}, userId={}", id, userId, e);
            return Result.error("删除俱乐部失败：" + e.getMessage());
        }
    }

    @Operation(summary = "获取俱乐部待审批成员", description = "只有创建者和管理员可以查看")
    @GetMapping("/{id}/pending-members")
    public Result<List<Map<String, Object>>> getPendingMembers(@PathVariable Long id) {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            return Result.error("请先登录");
        }

        try {
            // 查询俱乐部
            Club club = clubService.getById(id);
            if (club == null) {
                return Result.error("俱乐部不存在");
            }

            // 检查是否是创建者或管理员
            boolean isCreator = club.getCreatorId().equals(userId);
            boolean isAdmin = clubMemberService.isMember(userId, id) && 
                             clubMemberService.getMemberRole(userId, id).equals("admin");

            if (!isCreator && !isAdmin) {
                return Result.error("无权查看待审批成员");
            }

            // 查询待审批成员
            List<ClubMember> pendingMembers = clubMemberService.getClubMembers(id, "pending");

            if (pendingMembers.isEmpty()) {
                return Result.success(new ArrayList<>());
            }

            // 组装成员详细信息
            List<Map<String, Object>> memberDetails = new ArrayList<>();
            for (ClubMember member : pendingMembers) {
                User user = userMapper.selectById(member.getUserId());
                if (user != null) {
                    Map<String, Object> memberInfo = new HashMap<>();
                    memberInfo.put("memberId", member.getId());
                    memberInfo.put("userId", user.getId());
                    memberInfo.put("nickname", user.getNickname());
                    memberInfo.put("avatar", user.getAvatar());
                    memberInfo.put("status", member.getStatus());
                    memberInfo.put("appliedAt", member.getJoinedAt());
                    memberDetails.add(memberInfo);
                }
            }

            return Result.success(memberDetails);
        } catch (Exception e) {
            log.error("获取待审批成员失败: clubId={}", id, e);
            return Result.error("获取待审批成员失败");
        }
    }

    @Operation(summary = "审批俱乐部成员申请", description = "只有创建者和管理员可以审批")
    @PostMapping("/{id}/approve-member")
    public Result<Void> approveMember(
            @PathVariable Long id,
            @RequestParam Long memberId,
            @RequestParam Boolean approve) {
        
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {
            return Result.error("请先登录");
        }

        try {
            // 查询俱乐部
            Club club = clubService.getById(id);
            if (club == null) {
                return Result.error("俱乐部不存在");
            }

            // 检查是否是创建者或管理员
            boolean isCreator = club.getCreatorId().equals(userId);
            boolean isAdmin = clubMemberService.isMember(userId, id) && 
                             clubMemberService.getMemberRole(userId, id).equals("admin");

            if (!isCreator && !isAdmin) {
                return Result.error("无权审批成员申请");
            }

            // 查询成员申请
            ClubMember member = clubMemberService.getById(memberId);
            if (member == null || !member.getClubId().equals(id)) {
                return Result.error("成员申请不存在");
            }

            if (!"pending".equals(member.getStatus())) {
                return Result.error("该申请已被处理");
            }

            // 更新成员状态
            if (approve) {
                member.setStatus("active");
                member.setRole("member");
                log.info("俱乐部成员申请已通过: clubId={}, memberId={}, approver={}", id, memberId, userId);
            } else {
                member.setStatus("rejected");
                log.info("俱乐部成员申请已拒绝: clubId={}, memberId={}, approver={}", id, memberId, userId);
            }

            boolean success = clubMemberService.updateById(member);

            if (success) {
                // 如果通过，更新俱乐部成员数
                if (approve) {
                    club.setCurrentMembers(club.getCurrentMembers() + 1);
                    clubService.updateById(club);
                }
                return Result.success(approve ? "已通过申请" : "已拒绝申请", null);
            } else {
                return Result.error("审批失败");
            }
        } catch (Exception e) {
            log.error("审批成员申请失败: clubId={}, memberId={}", id, memberId, e);
            return Result.error("审批失败：" + e.getMessage());
        }
    }
}
